clear all;
clc;

tic
disp('Loading data...');
load 7nnsmall;

k = 7;
s = 30;
lam = 1;

l = 5000;

C = 10;
c = 10;

Y = yU(1:l)';

disp('Data loaded!');

n = size(V,1);

nump = c*(c-1)/2;
sz = zeros(c,1);
for i = 0:c-1
    eval(['idx',int2str(i),'=find(Y==i);']);
    eval(['sz(i+1) = size(idx',int2str(i),',1);']);
end

for i = 0:c-1
    for j = i+1:c-1
        eval(['ix=[idx',int2str(i),';idx',int2str(j),'];']);
        eval(['P',int2str(i),int2str(j),'=repmat(Y(ix,:),1,s).*V(ix,:);']);
    end
end
clear Y;
Q = V(l+1:n,:);
clear V;

disp('Start optimization...');
tic

ct = 1;
cvx_begin sdp
cvx_solver sedumi
    variable t
    variable gam(s,nump)
    variable M(s,s) symmetric
    variable del nonnegative
    minimize (t);
    for i = 0:c-1
        for j = i+1:c-1
            [M gam(:,ct);gam(:,ct)' t-2*C*del] >= 0;
            var = ['P',int2str(i),int2str(j)];
            eval([var,'*gam(:,ct) >= ones(size(',var,',1),1)-del']);
            ct=ct+1;
        end
    end
cvx_end

toc

Yp = zeros(n-l,1);

for trn = 1:size(Q,1)
    vt = zeros(c,1);
    ct = 1;
    for i = 1:c
        for j = i+1:c
            if (Q(trn,:)*gam(:,ct) > 0)
                vt(i)=vt(i)+1;
            else vt(j)=vt(j)+1;
            end
        end
    end
    [~,Yp(trn)] = max(vt);
end

Yp = uint8(Yp)-1;

label = int8(yU(l+1:n)');
calacc(Yp,label)
